package com.primb.bench.common.override;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.orhanobut.logger.Logger;
import com.primb.baselibs.util.NetworkUtils;
import com.primb.bench.R;
import com.primb.bench.base.IApplication;
import com.primb.bench.project.init.activity.LoginActivity;
import com.primb.bench.project.init.activity.SplashActivity;
import com.primb.netlibs.exception.ApiException;
import com.primb.netlibs.exception.ERROR;
import com.primb.netlibs.exception.ExceptionEngine;
import com.primb.netlibs.exception.ResultException;

import rx.Subscriber;

import static com.primb.netlibs.exception.ExceptionEngine.LOGIN_TIMEOUT;


/**
 * Created by Chen on 2017/6/19.
 * 功能描述：
 */

public abstract class HttpSubscriber<T> extends Subscriber<T> {
    private Context mContext;

    public HttpSubscriber(Context context) {
        this.mContext = context;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!NetworkUtils.isNetworkConnected(mContext)) {
            Toast.makeText(mContext, "没有网络连接，请检查后重试", Toast.LENGTH_SHORT).show();
            onCompleted();
            return;
        }
    }

    @Override
    public void onError(Throwable e) {
        if (e instanceof Exception) {
            ApiException apiException = ExceptionEngine.handleException(e);
            if (apiException.code == LOGIN_TIMEOUT) {
                showAlterDialog("提示", apiException.getMessage());
                return;
            } else {
                onError(apiException);
            }
        } else {
            //将Throwable 和 未知错误的status code返回
            onError(new ApiException(e, ERROR.UNKNOWN));
        }
    }

    public abstract void onError(ApiException e);

    public NormalDialog showAlterDialog(String title, String message) {
        NormalDialog dialog = new NormalDialog(mContext);
        dialog.widthScale(0.8f);
        dialog.style(NormalDialog.STYLE_TWO);
        dialog.titleLineColor(ContextCompat.getColor(mContext, R.color.app_main_gray));
        dialog.title(title);
        dialog.btnNum(1);
        dialog.content(message);
        dialog.dividerColor(ContextCompat.getColor(mContext, R.color.app_main_gray));
        dialog.btnText("确定");
        dialog.show();
        dialog.setCancelable(false);
        dialog.setOnBtnClickL((OnBtnClickL) () -> {
            //重新启动app
            Intent intent = new Intent(mContext, LoginActivity.class);
            mContext.startActivity(intent);
        });
        return dialog;
    }
}
